<?php

/**
 * cart actions.
 *
 * @package    sf_sandbox
 * @subpackage cart
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */
class cartActions extends sfActions
{
  public function executeIndex($request)
  {
  }

  public function executeAdd($request)
  {
    $tmp = split('_', $this->getRequestParameter('id', ''));
    $product_id = $tmp[1];
    $cart = $this->getUser()->getAttribute('cart');
    if (!isset($cart[$product_id]))
  {
    $cart[$product_id] = 1;
  }
  else
  {
    ++$cart[$product_id];
  }
    $this->getUser()->setAttribute('cart', $cart);
  }
  
  public function executeRemove()
  {
    $product_id = $this->getIdFromRequest();
    $cart = $this->getUser()->getAttribute('cart');
    if (isset($cart[$product_id]) && $cart[$product_id] > 1)
    {
      --$cart[$product_id];
    }
    else
    {
      unset($cart[$product_id]);
    }
    $this->getUser()->setAttribute('cart', $cart);
  }
  
  public function executeAddAjax($request)
  {
    $tmp = split('_', $this->getRequestParameter('id', ''));
    $product_id = $tmp[1];
    $cart = $this->getUser()->getAttribute('cart');
    if (!isset($cart[$product_id]))
  {
    $cart[$product_id] = 1;
  }
  else
  {
    ++$cart[$product_id];
  }
    $this->getUser()->setAttribute('cart', $cart);
    $this->forward('cart', 'index');
  }
  
  public function executeRemoveAjax()
  {
    $tmp = split('_', $this->getRequestParameter('id', ''));
    $product_id = $tmp[1];
    $cart = $this->getUser()->getAttribute('cart');
    if (isset($cart[$product_id]) && $cart[$product_id] > 1)
    {
      --$cart[$product_id];
    }
    else
    {
      unset($cart[$product_id]);
    }
    $this->getUser()->setAttribute('cart', $cart);
    $this->forward('cart', 'index');
  }
  
  public function executeRemoveProductAjax()
  {
    $product_id = $this->getRequestParameter('id');
    $cart = $this->getUser()->getAttribute('cart');
    unset($cart[$product_id]);

    $this->getUser()->setAttribute('cart', $cart);
    $this->forward('cart', 'index');
  }
  
  public function executeClear()
  {
    $this->getUser()->setAttribute('cart', array());
    $this->forward('cart', 'index');
  }

  private function getIdFromRequest()
  {
    $id = $this->getRequestParameter('id', '');
    if (!$id)
    {
      return 0;
    }

    $tmp = split('_', $id);
    $product_id = $tmp[1];

    return $product_id;
  }
}

